package org.example.trigger.job;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.user_participate.repository.IUserParticipateRepo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author lxc18
 * @date 2025/3/15 21:05
 * @description UserActivityQuotaJob
 */
@Slf4j
@Component
public class UserActivityQuotaJob {

    @Resource
    private IUserParticipateRepo userParticipateRepo;
    @Resource
    private RedissonClient redissonClient;

    @XxlJob("UserActivityQuotaJobHandler")
    public void userActivityQuotaJobHandler() throws InterruptedException {
        // 分布式锁
        RLock lock = redissonClient.getLock("UserActivityQuotaJobHandler");
        try {
            boolean isLocked = lock.tryLock(3, 10, TimeUnit.SECONDS);
            if (!isLocked) {
                log.warn("未能获取锁，任务已被其他实例执行");
                return;
            }
            userParticipateRepo.updateCacheToDB();
            log.info("用户额度成功更新到数据库");
        } catch (Exception e) {
            log.error("定时任务更新用户额度失败", e);
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }


}
